#include "logmanager.h"
#include <QDebug>

// 初始化静态成员变量
LogManager* LogManager::m_instance = nullptr;

LogManager::LogManager(QObject *parent)
    : QObject(parent), logFile(nullptr), logStream(nullptr), logPath("log")
{
}

LogManager::~LogManager()
{
    closeLogFile();
}

LogManager* LogManager::instance()
{
    if (m_instance == nullptr) {
        m_instance = new LogManager();
    }
    return m_instance;
}

void LogManager::writeLog(const QString &message, const QString &level)
{
    // 获取当前时间
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

    // 构造日志行
    QString logLine = QString("[%1] [%2] %3\n").arg(timestamp).arg(level).arg(message);

    // 确保日志文件已打开
    if (!openLogFile()) {
        qDebug() << "Failed to open log file";
        return;
    }

    // 写入日志
    *logStream << logLine;
    logStream->flush(); // 确保立即写入文件
}

void LogManager::setLogPath(const QString &path)
{
    // 如果当前有打开的日志文件，先关闭它
    closeLogFile();

    logPath = path;
}

QString LogManager::getCurrentDate() const
{
    return QDateTime::currentDateTime().toString("yyyy-MM-dd");
}

bool LogManager::openLogFile()
{
    // 如果已经打开且是今天的文件，直接返回true
    if (logFile && logFile->isOpen()) {
        QString currentDate = getCurrentDate();
        QString expectedFileName = QString("%1/%2.txt").arg(logPath).arg(currentDate);
        if (logFile->fileName() == expectedFileName) {
            return true;
        }
        // 如果不是今天的文件，关闭当前文件
        closeLogFile();
    }

    // 确保日志目录存在
    QDir dir;
    if (!dir.exists(logPath)) {
        if (!dir.mkpath(logPath)) {
            qDebug() << "Failed to create log directory:" << logPath;
            return false;
        }
    }

    // 构造日志文件名
    QString currentDate = getCurrentDate();
    QString fileName = QString("%1/%2.txt").arg(logPath).arg(currentDate);

    // 创建或打开日志文件
    logFile = new QFile(fileName);
    if (!logFile->open(QIODevice::WriteOnly | QIODevice::Append)) {
        qDebug() << "Failed to open log file:" << fileName;
        delete logFile;
        logFile = nullptr;
        return false;
    }

    // 创建文本流
    logStream = new QTextStream(logFile);
    return true;
}

void LogManager::closeLogFile()
{
    if (logStream) {
        delete logStream;
        logStream = nullptr;
    }

    if (logFile) {
        if (logFile->isOpen()) {
            logFile->close();
        }
        delete logFile;
        logFile = nullptr;
    }
}
